package sagroup.dracots;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * The log formatter used by DracoTS
 * @author Xing Jiankuan
 *
 */
public class DracoTSFormatter extends Formatter {

	Date dat = new Date();
    private final static String format = "{0,date},{0,time,HH:mm:ss:SSS},";
    private MessageFormat formatter;
    private Object args[] = new Object[1];
    private final String separator = System.getProperty("line.separator");
    
	@Override
	public String format(LogRecord record) {
		StringBuffer sb = new StringBuffer();
		// Minimize memory allocations here.
		dat.setTime(record.getMillis());
		args[0] = dat;
		StringBuffer text = new StringBuffer();
		if (formatter == null) {
		    formatter = new MessageFormat(format);
		}
		formatter.format(args, text, null);
		sb.append(text);
		String message = formatMessage(record);
		sb.append(message);
		sb.append(separator);
		if (record.getThrown() != null) {
		    try {
		        StringWriter sw = new StringWriter();
		        PrintWriter pw = new PrintWriter(sw);
		        record.getThrown().printStackTrace(pw);
		        pw.close();
			sb.append(sw.toString());
		    } catch (Exception ex) {
		    }
		}
		return sb.toString();
	}
}
